import { globalConfig } from "../config/global";
import { State } from "../core/state";
import { TextualState } from "../core/textual_state";
import { waitNextFrame } from "../core/utils/utils";
import { GameDataCreate } from "../game/game_data_create";
import { getRandomHint } from "../game/hints";
import { talentsDefine } from "../game/defines/talents_define";
import { demonRace, genderDefine, humanRace, RaceDefine } from "../game/defines/race_define";

const options = {
  gender: {
    title: '性别',
    desc: '影响角色性别',
    options: {
      [genderDefine.male]: { text: '男性', desc: '选择这个表示你是一个男人。' },
      [genderDefine.female]: { text: '女性', desc: '选择这个表示你是一个女人。' },
    },
    activeNum: 1
  },
  race: {
    title: '种族',
    desc: '影响角色的初始种族',
    options: {
      human: humanRace,
      demon: demonRace
    },
    activeNum: 1
  },
  talents: {
    title: '天赋',
    desc: '影响角色更擅长哪个方面（可选两个）',
    options: talentsDefine,
    activeNum: 2
  }
}

export class GameCreateState extends TextualState{
  constructor(){
    super('GameCreateState')
  }

  getStateHeaderTitle(){
    return '玩家创建'
  }

  getMainContentHTML(){
    return `
    <div class="group">
      <div class="title">
        <h2>姓名</h2>
        <span>影响角色的名字(最多四个汉字)</span>
      </div>

      <div class="options">
        <input id="playerName" type="text" placeholder="输入你的名字">
      </div>
    </div>

    <div class="group-options">
    </div>

    <div class="group createGame">
      <button class="styledButton">开始游戏</button>
    </div>
    `
  }

  onEnter(){
    this.initOption();
    this.initOptionButton();

    const playerNameInput = this.htmlElement.querySelector('#playerName');
    playerNameInput.addEventListener('input', (ev) => {
      this.activeOption.playerName = playerNameInput.value;
    })

    if(G_IS_DEV && globalConfig.debug.createGameDefaultData){
      this.createGame();
    }

    this.trackClicks(this.htmlElement.querySelector('.createGame button'), () => {
      this.createGame();
    })
  }

	// onRender() {
  //   if(!this.loadingElment) return;
  //   const now = performance.now();
  //   if(now - this.lastHintShown > this.nextHintDuration){
	// 		this.lastHintShown = now;
  //     const hintText = getRandomHint();

	// 		this.loadingElment.innerHTML = hintText;

	// 		/**
  //      * 以每分钟500个字符的阅读速度计算
	// 		 */
	// 		this.nextHintDuration = Math.max(2500, (hintText.length / 500) * 60 * 1000);
	// 	}
  // }

  createGame(){
    if(G_IS_DEV && globalConfig.debug.createGameDefaultData){
      this.activeOption = {
        playerName: '测试员',
        gender: [genderDefine.male],
        race: [RaceDefine.human.key],
        talents: ['skilling', 'running']
      }
    }

    if(!this.checkData()){
      return;
    }

    let closeFn = this.dialogs.showGameLoadingDialog('数据创建中...');

    new GameDataCreate(this.activeOption, data => {
      setTimeout(() => {
        Promise.all([
          this.app.savegame.saveData(data)
        ])
        .then(() => {
          closeFn();
          this.moveToState('GameState');
        })
        // this.app.savegame.writeAsync().then(() => {
        // })
      }, 1000);
    });
  }

  checkData(){
    // 判断名字是否正确
    if(!/^[\u4e00-\u9fa5]{1,4}$/.test(this.activeOption.playerName)){
      this.dialogs.showWarning('姓名错误', '姓名只能为中文并且最多四个汉字。');
      return false;
    }

    // 判断其他选项是否填选
    if(
      this.activeOption.gender.length <= 0 ||
      this.activeOption.race.length <= 0 ||
      this.activeOption.talents.length <= 0
    ){
      this.dialogs.showWarning('性别/性格/种族/天赋错误', '性别/性格/种族/天赋你没有选中项。');
      return false;
    }

    return true;
  }

  initOption(){
    let optionHtml = ``;
    this.activeOption = {};

    Object.keys(options).forEach(key => {
      const option = options[key];
      optionHtml += `
      <div class="group">
        <div class="title">
          <h2>${option.title}</h2>
          <span>${option.desc}</span>
        </div>
        <div class="options">
          ${
            Object.keys(option.options).map(btnKey => 
              `<button class="styledButton noPressEffect" data-option="${key}" data-option-value="${btnKey}">${option.options[btnKey].text}</button>`
            ).join('')
          }
        </div>
        <div data-option-desc="${key}" class="description">
          待选择
        </div>
      </div>
      `

      this.activeOption[key] = [];
    }) 
    
    this.htmlElement.querySelector('.group-options').innerHTML = optionHtml;
  }

  initOptionButton(){
    const buttons = this.htmlElement.querySelectorAll(`[data-option]`)

    buttons.forEach(button => {
      this.trackClicks(button, (pos, ev) => {
        button.focus();
        this.setActiveOption(button);
      })
    })
  }

  /**
   * 
   * @param {HTMLElement} button 
   */
  setActiveOption(button){
    const option = button.getAttribute('data-option');
    const optionValue = button.getAttribute('data-option-value');

    assert(options[option], '创建角色的选项不存在');

    if(this.activeOption[option].indexOf(optionValue) >= 0) return;

    button.classList.add('active');
    this.activeOption[option].push(optionValue);

    if(this.activeOption[option].length > options[option].activeNum){
      const prevActive = this.activeOption[option].shift();
      this.htmlElement.querySelector(`[data-option-value="${prevActive}"]`).classList.remove('active');
    }

    const optionDesc = this.htmlElement.querySelector(`[data-option-desc="${option}"]`);

    optionDesc.innerHTML = this.activeOption[option].map(key => `
      <p>${options[option].options[key].desc}</p>
    `).join('')
  }
}